package com.wangrui.test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.wangrui.dao.UserMapper7;
import com.wangrui.entity.UserCountParam;

public class MyBatisTest07 {

    /**
     * 获得MyBatis SqlSessionFactory
     * SqlSessionFactory负责创建SqlSession，一旦创建成功，就可以用SqlSession实例来执行映射语句
     * ，commit，rollback，close等方法。
     *
     * @return
     */
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {

            e.printStackTrace();
        }
        return sessionFactory;
    }


    @Test
    public void testProcedure() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();
        UserMapper7 userMapper = session.getMapper(UserMapper7.class);
        Map<String, Integer> paramMap = new HashMap<String, Integer>();
        paramMap.put("sex_id", 1);
        paramMap.put("user_count", -1);
        userMapper.getCount(paramMap);
        System.out.println(paramMap.get("user_count"));
    }

    /**
     * 调用存储过程不一定要用Map，用普通的java类也可以
     */
    @Test
    public void testProcedure2() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();
        UserMapper7 userMapper = session.getMapper(UserMapper7.class);
        UserCountParam param = new UserCountParam();
        param.setSex_id(2);
        userMapper.getCount2(param);
        System.out.println(param.getUser_count());
    }
}
